package com.situ.ssm.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.situ.ssm.entity.Department;
import com.situ.ssm.entity.Role;
import com.situ.ssm.entity.User;
import com.situ.ssm.entity.UserRoleDepartment;
import com.situ.ssm.entity.UserSearchBO;
import com.situ.ssm.mapper.UserMapper;
import com.situ.ssm.service.IUserService;
import com.situ.ssm.util.JSONResult;

@Service
public class UserServiceImpl implements IUserService{
	@Autowired
	private UserMapper userMapper;

	@Override
	public JSONResult selectAll(Integer page, Integer limit, UserSearchBO userSearchBO) {
		int offset = (page - 1) * limit;
		List<UserRoleDepartment> list = userMapper.selectAll(offset, limit, userSearchBO);
		
		int count = userMapper.selectTotalCount(userSearchBO);
		
		return JSONResult.success(list, count);
	}

	@Override
	public List<Role> selectRole() {
		List<Role> list = userMapper.selectRole();
		return list;
	}

	@Override
	public List<Department> selectDepartment() {
		List<Department> list = userMapper.selectDepartment();
		return list;
	}

	@Override
	public User selectId(Integer id) {
		User user = userMapper.selectId(id);
		return user;
	}

	@Override
	public List<Integer> selectRoleIdByUser(Integer id) {
		List<Integer> list = userMapper.selectRoleIdByUser(id);
		return list;
	}

	@Override
	public boolean insert(User user, String[] roleId) {
		int count = 0;
		userMapper.insert(user);
		int userId = userMapper.selectGetId(user.getEmail());
		System.out.println(userId);
		for (String string : roleId) {
			userMapper.insertUR(userId, Integer.parseInt(string));
			count++;
		}
		return count == roleId.length;
	}

	@Override
	public boolean delete(Integer id) {
		int count = userMapper.delete(id);
		userMapper.deleteUR(id);
		return count == 1;
	}

	@Override
	public boolean update(User user, Integer id, String[] roleId) {
		int count1 = userMapper.update(user);
		userMapper.deleteUR(id);
		for (String string : roleId) {
			userMapper.insertUR(id, Integer.parseInt(string));
		}
		return count1 == 1;
	}

	@Override
	public boolean deleteAll(String[] ids) {
		int count = 0;
		for (String id : ids) {
			count += userMapper.delete(Integer.parseInt(id));
		}
		return count == ids.length;
	}

}
